<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（上海）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use app\erp\model\ErpGoods;
use think\Db;
use app\common\builder\ZBuilder;
use util\Tree;
use function GuzzleHttp\Psr7\str;

/**
 * 储值管理
 * @author dou <51779987@qq.com>
 * @package app\cms\admin
 */
class Balance extends Admin
{
    /**
     * 储值订单-记录&统计
     * @author dou <51779987@qq.com>
     * @param string $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function record()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        if(empty($map)||in_array('j.pay_status',$map)){
            $map[] = ['j.pay_status','=','1'];
        }
        //数据获取
        $data = input();
        //数据列表
        $data_list =model('user_center/UcMemberBalance', 'model\user')->getInfo($map);
        if($data_list['code'] > 0){
            $data_list_total = $data_list['data']['total'];
            $data_list_info = $data_list['data']['info'];
        }else{
            $data_list_total = [];
            $data_list_info = [];
        }
        $tips  = "*储蓄总金额：用户储值的总金额<br/>";
        $tips .= "<pre>";
        $tips .= "储蓄人数：<strong style='color: red'>".intval($data_list_total['total_uid'])."</strong>（人）<br/>";
        $tips .= "储蓄订单数：<strong style='color: red'>".intval($data_list_total['total_order'])."</strong>（单）<br/>";
        $tips .= "储蓄总金额：<strong style='color: red'>".number_format($data_list_total['total_price'],2)."</strong>（￥）<br/>";
/*        $tips .= "储蓄总支出：<strong style='color: red'>".number_format($data_list_total['total_price_e'],2)."</strong>（￥）<br/>";
        $tips .= "储蓄余额：<strong style='color: red'>".number_format($data_list_total['total_price_in']-$data_list_total['total_price_e'],2)."</strong>（￥）<br/>";*/
        $tips .= "</pre>";

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('储值记录管理') // 设置页面标题
            ->setPageTips($tips, 'success')
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('uc_member_balance_journal_log') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'], 0  1 2 3 4
                ['pay_status', '订单状态','status', '', [0=>'待支付:primary',1 => '已支付:info', 2 => '已完成:success',3 => '已取消:danger',4=>'已过期:warning']],
                /*['id', '储值单id'],*/
                ['pay_order_id', '订单号'],
                ['order_code', '订单编号'],
                ['nick_name', '储值人', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['pay_price', '订单金额'],
               /* ['song_price', '总赠送金额'],*/
                ['pay_type', '支付方式',[0=>'手动充值',1=>'微信',2=>'支付宝']],
               /* ['ine', '类别',[0=>'收入',1=>'支出']],
                ['price', '金额','text'],
                ['log_remark', '说明'],*/
                ['create_time', '下单时间' ,'datetime'],
            ])
            ->setSearchArea([
                ['select', 'j.pay_status', '支付状态', '=',1,[0=>'待支付',1 => '已支付', 2 => '已完成',3 => '已取消',4=>'已过期'],1],
                ['select', 'j.pay_type', '支付方式', '=','',[0=>'手动充值',1=>'微信',2=>'支付宝']],
                ['text', 'u.nick_name', '会员名', 'like'],
                ['daterange', 'j.create_time', '订单时间']
            ])
            ->addColumn('right_button', '操作', 'btn')
            ->addRightButton('custom', ['title' => '明细列表', 'href' => url('erp/balance/record_log', ['journal_id' => '__id__'])],true)
            ->setRowList($data_list_info) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 储值流水明细
     * @author dou <51779987@qq.com>
     * @param string $journal_id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function record_log($journal_id='')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        $map['journal_id'] = $journal_id;
        //数据获取
        $data = input();
        //数据列表
        $data_list =model('user_center/UcMemberBalanceJournalLog', 'model\user')->where($map) -> order('create_time desc') -> paginate();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('储值记录流水管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('uc_member_balance_journal_log') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['id', 'ID'],/*
                ['journal_id', '储值单id'],*/
                /*['uid', '储值人'],*/
                ['ine', '类别', 'status', '', [1 => '充值:success', 2 => '赠送:warning',3 => '消费:danger']],
                ['price', '金额','text'],
                ['log_remark', '说明'],
                ['create_time', '获取时间' ,'datetime'],
            ])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }


    /**
     * 储值流水-统计
     * @author dou <51779987@qq.com>
     */
    public function balance_statistics(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        foreach ($map as $key => $value) {
            if($value[0] == 'nick_name'){
                $map1 = [];
                $map1[] = $value; 
                $rel = model('user_center/Member', 'model\user') -> where($map1) -> column('uid');
                
                $map[$key] = ['uid', 'in', $rel];
            }
        }

        //数据列表
        $rel_list = [];
        //$data_list =model('user_center/UcMemberBalance', 'model\user')->getAllInfo($map);
        $data_list = model('user_center/UcMemberBalanceJournalLog', 'model\user')->where($map)->order('create_time desc') -> select();
        foreach ($data_list as $key => $value) {
            $rel_list[$key] = $value;
            $rel_list[$key]['nick_name'] = $value -> get_uc_member -> nick_name;
            //if(!isset($value -> get_uc_member_balance)) continue;
            //$rel_list[$key]['order_code'] = $value -> get_uc_member_balance -> order_code;
            

        }

        //储值人数
        $map = [];
        $map[] = ['ine', '=', 1];
        $total_uid = model('user_center/UcMemberBalanceJournalLog', 'model\user')->where($map) -> group('uid') -> count();
        //充值金额
        $map = [];
        $map[] = ['ine', '=', 1];
        $total_price = model('user_center/UcMemberBalanceJournalLog', 'model\user')->where($map)  -> sum('price');
        //赠送
        $map = [];
        $map[] = ['ine', '=', 2];
        $total_price_in = model('user_center/UcMemberBalanceJournalLog', 'model\user')->where($map)  -> sum('price');
        //消费
        $map = [];
        $map[] = ['ine', '=', 3];
        $total_price_e = model('user_center/UcMemberBalanceJournalLog', 'model\user')->where($map)  -> sum('price');
   
    
        $tips  = "*&nbsp;储蓄余额=（充值流水+赠送流水）- 消费流水<br/>";
        $tips .= "<pre>";
        $tips .= "储蓄人数：<strong style='color: red'>".intval($total_uid)."</strong>（人）<br/>";
        $tips .= "储蓄流水-充值：<strong style='color: red'>".number_format($total_price, 2)."</strong>（￥）<br/>";
        $tips .= "储蓄流水-赠送：<strong style='color: red'>".number_format($total_price_in, 2)."</strong>（￥）<br/>";
        $tips .= "储蓄流水-消费：<strong style='color: red'>".number_format($total_price_e, 2)."</strong>（￥）<br/>";
        /*if(!empty($map)){
            if(!in_array('ine',$map[0],true)){
                $tips .= "储蓄余额：<strong style='color: red'>".number_format(($total_price+$total_price_in)-$total_price_e,2)."</strong>（￥）<br/>";
            }
        }else{
            $tips .= "储蓄余额：<strong style='color: red'>".number_format(($total_price + $total_price_in)-$total_price_e,2)."</strong>（￥）<br/>";
        }*/

        $tips .= "</pre>";

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('储值流水统计') // 设置页面标题
            ->setPageTips($tips, 'success')
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['ine', '类别', 'status', '', [1 => '充值:success', 2 => '赠送:warning',3 => '消费:danger']],
                /*['id', '储值单id'],*/
                //['order_code', '订单编号'],
                /*['nick_name', '储值人'],*/
                ['nick_name', '储值人', 'link', url('user_center/index/details', ['uid' => '__uid__']), '_blank', 'pop'],
                ['price', '金额','text'],
                ['log_remark', '说明'],
                ['create_time', '下单时间' ,'datetime'],
            ])
            ->setSearchArea([
                ['select', 'ine', '类型', '=','',[1 => '充值', 2 => '赠送',3 => '消费']],
                ['text', 'nick_name', '会员名', 'like'],
                ['daterange', 'create_time', '获取时间']
            ])
            ->setRowList($rel_list) // 设置表格数据
            ->fetch(); // 渲染页面
    }

    /**
     * 首页-规则
     * @author  dou<51779987@qq.com>
     * @return mixed
     */
    public function index_rule()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
        //数据列表
        $data_list = model('user_center/UcMemberBalanceRules', 'model\user')->where($map) -> order('create_time desc') -> paginate();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('储蓄规则管理') // 设置页面标题
            ->setPrimaryKey('id') // 设置主键名为id
            ->setTableName('uc_member_balance_rules') // 设置数据表名
            ->addColumns([ // 批量添加列
                // ['__INDEX__', '序号'],
                ['id', '规则ID'],
                ['name', '储蓄名称', 'text.edit'],
                ['man_price', '储蓄金额', 'text.edit'],
                ['song_price', '储蓄赠送', 'text.edit'],
                ['level', '规则权重', 'text.edit']
            ])
            ->addColumn('create_time', '创建时间', 'datetime','datetime')
            ->addColumn('status', '启用', 'switch')
            //->addColumn('superpose', '叠加使用', 'switch')
            ->addColumn('right_button', '操作', 'btn')
            ->setSearchArea([
                ['text', 'id', '规则ID'],
                ['text', 'name', '储蓄名称', 'like']
            ])
            ->addTopButton('add', ['title' => '新增规则', 'href' => url('erp/balance/add_rule')], ['area' => ['50%', '80%']]) // 添加授权按钮
            ->addRightButton('edit', ['title' => '编辑规则', 'href' => url('erp/balance/edit_rule', ['id' => '__id__'])], ['area' => ['50%', '80%']]) // 添加授权按钮
            ->addTopButton('delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面

    }


    /**
     * 添加储值规则
     * @author dou <51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add_rule()
    {
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post();
            $user_id                = intval(isset($data['user_id']) ? $data['user_id'] : 1);
            $name                   = strval(isset($data['name']) ? $data['name'] : '');
            $man_price  		    = strval(isset($data['man_price']) ? $data['man_price'] : 0);
            $song_price             = strval(isset($data['song_price']) ? $data['song_price'] : 0);
            $level  		        = intval(isset($data['level']) ? $data['level'] : 100);
            $status  		        = intval(isset($data['status']) ? $data['status'] : 1);
            $superpose  		    = intval(isset($data['superpose']) ? $data['superpose'] :1);

            //数据验证
            $Validate = validate('Balance', 'validate');
            if( !$Validate -> scene('balance_rule_add') -> check($data) ){
                $this->error($Validate -> getError());
            }else{}

            $rel = model('user_center/UcMemberBalanceRules', 'model\user') -> addData($name, $man_price, $song_price, $level, $status, $superpose);

            if($rel['code'] == 200){
                $this->success('新增成功', '', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增储蓄规则') // 设置页面标题
            ->addText('name','储值名称','如 ：满100送20')
            ->addText('man_price','请输入储蓄满足条件值')
            ->addText('song_price','请输入储蓄赠送值')
            ->addText('level','请输入规则等级','数值越小权重越高',100)
            ->addRadio('status', '是否可用','当储蓄规则不可用时储蓄不享受福利',['不可用','可用'],1)
            ->addRadio('superpose', '是否可以叠加使用','当储蓄规则不可叠加用时，不可享受多个福利',['不可叠加','可叠加'],0)
            ->fetch();
    }


    /**
     * 编辑储值规则
     * @author dou <51779987@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit_rule($id=[])
    {
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post();
            $data['id'] = $id;
            $user_id                = intval(isset($data['user_id']) ? $data['user_id'] : 1);
            $name                   = strval(isset($data['name']) ? $data['name'] : '');
            $man_price  		    = strval(isset($data['man_price']) ? $data['man_price'] : 0);
            $song_price             = strval(isset($data['song_price']) ? $data['song_price'] : 0);
            $level  		        = intval(isset($data['level']) ? $data['level'] : 100);
            $status  		        = intval(isset($data['status']) ? $data['status'] : 1);
            $superpose  		    = intval(isset($data['superpose']) ? $data['superpose'] :1);
            

            //数据验证
            $Validate = validate('Balance', 'validate');
            if( !$Validate -> scene('balance_rule_edit') -> check($data) ){
                $this->error($Validate -> getError());
            }else{}

            $rel = model('user_center/UcMemberBalanceRules', 'model\user') -> editData($id, $name, $man_price, $song_price, $level, $status, $superpose);

            if($rel['code'] == 200){
                $this->success('编辑成功', '', '_parent_reload');
            }else{
                $this->error($rel['message']);
            }

        }

        // 使用ZBuilder快速创建表单
        $map = $this->getMap();
        $info = model('user_center/UcMemberBalanceRules', 'model\user') -> find($id);
        return ZBuilder::make('form')
            ->setPageTitle('编辑储蓄规则') // 设置页面标题
            ->addText('name','储值名称','如 ：满100送20')
            ->addText('man_price','请输入储蓄满足条件值')
            ->addText('song_price','请输入储蓄赠送值')
            ->addText('level','请输入规则等级','数值越小权重越高')
            ->addRadio('status', '是否可用','当储蓄规则不可用时储蓄不享受福利',['不可用','可用'],1)
            ->addRadio('superpose', '是否可以叠加使用','当储蓄规则不可叠加用时，不可享受多个福利',['不可叠加','可叠加'],0)
            ->setFormData($info)
            ->fetch();
    }

    public function delete_rule($ids = []){
        $rel = model('user_center/UcMemberBalanceRules', 'model\user') -> deleteData($ids);

        $this->success('删除成功');
    }
}